#ifndef _ONLINE_H__
#define _ONLINE_H__
#include "util.hpp"
#include <mutex>
#include <unordered_map>

class online_manager{
    private:
        std::mutex _mutex;
        std::unordered_map<uint64_t, wsserver_t::connection_ptr> _hall_user;//建立游戏大厅用户ID于通信连接的关系
        std::unordered_map<uint64_t, wsserver_t::connection_ptr> _room_user;//建立游戏房间用户ID于通信连接的关系
    public:
        //websoket连接建立的时候才会加入游戏大厅&游戏房间的在线用户管理
        bool enter_game_hall(uint64_t uid, wsserver_t::connection_ptr& connection)
        {
            std::unique_lock<std::mutex> lock(_mutex);
            _hall_user.insert(std::make_pair(uid, connection));
        }
        bool enter_game_room(uint64_t uid, wsserver_t::connection_ptr& connection)
        {
            std::unique_lock<std::mutex> lock(_mutex);
            _room_user.insert(std::make_pair(uid, connection));            
        }
        //断开连接的时候移除大厅或房间
        bool exit_game_hall(uint64_t uid)
        {
            std::unique_lock<std::mutex> lock(_mutex);
            _hall_user.erase(uid);
            std::cout << uid << " 已被移除大厅" << std::endl;
        }
        bool exit_game_room(uint64_t uid)
        {
             std::unique_lock<std::mutex> lock(_mutex);
            _room_user.erase(uid);
            std::cout << uid << " 已被移除房间" << std::endl;
        }
        //判断是否在游戏大厅或房间
        bool is_in_game_hall(uint64_t uid)
        {
            std::unique_lock<std::mutex> lock(_mutex);
            auto it = _hall_user.find(uid);
            if(it == _hall_user.end())
            {
                return false;
            }
            return true;
        }
        bool is_in_game_room(uint64_t uid)
        {
            std::unique_lock<std::mutex> lock(_mutex);
            auto it = _room_user.find(uid);
            if(it == _room_user.end())
            {
                return false;
            }
            return true;
        }
        //通过id获取对应的连接
        wsserver_t::connection_ptr get_conn_from_hall(uint64_t uid)
        {
            std::unique_lock<std::mutex> lock(_mutex);
            auto it = _hall_user.find(uid);
            if(it == _hall_user.end())
            {
                return wsserver_t::connection_ptr();
            }
            return it->second;
        }
        wsserver_t::connection_ptr get_conn_from_room(uint64_t uid)
        {
            std::unique_lock<std::mutex> lock(_mutex);
            auto it = _room_user.find(uid);
            if(it == _room_user.end())
            {
                return wsserver_t::connection_ptr();
            }
            return it->second;
        }
};

#endif